package com.tepth.remote.control.delegate.pick;

import android.annotation.SuppressLint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.blankj.utilcode.util.ToastUtils;
import com.tencent.bugly.crashreport.BuglyLog;
import com.tencent.bugly.crashreport.CrashReport;
import com.tepth.remote.control.R;
import com.tepth.remote.control.R2;
import com.tepth.remote.control.base.bean.Config;
import com.tepth.remote.control.base.bean.ElementBean;
import com.tepth.remote.control.base.bean.Fences;
import com.tepth.remote.control.base.bean.Project;
import com.tepth.remote.control.base.config.ApiDictionary;
import com.tepth.remote.control.base.convert.ObjectConverter;
import com.tepth.remote.control.base.event.LocationEvent;
import com.tepth.remote.control.base.map.overlay.BitmapDescriptorBuilder;
import com.tepth.remote.control.base.map.overlay.DrawOverlay;
import com.tepth.remote.control.base.map.overlay.MarkerOverlay;
import com.tepth.remote.control.base.xml.XmlHandler;
import com.tepth.remote.control.delegate.BasePermissionCheckerDelegate;
import com.tepth.remote.control.delegate.attendance.AttendanceDelegate;
import com.tepth.remote.control.manager.ConfigManager;
import com.tepth.remote.core.app.Control;
import com.tepth.remote.core.net.callback.IError;
import com.tepth.remote.core.net.callback.ISuccess;
import com.tepth.remote.core.net.retrofit.RxRetrofitClient;
import com.tepth.remote.core.utils.file.FileUtil;
import com.tepth.remote.core.utils.resources.ResourcesUtil;
import com.tepth.remote.core.utils.thread.ControlSingleThread;
import com.tepth.remote.core.utils.thread.RunnableCallback;
import com.tepth.remote.ui.alert.DialogLoader;
import com.tepth.remote.ui.alert.IDialogClickListener;
import com.tepth.remote.ui.recycler.MultipleFields;
import com.tepth.remote.ui.recycler.MultipleItemEntity;
import com.tepth.remote.ui.recycler.MultipleRecyclerAdapter;
import com.tepth.remote.ui.recycler.MultipleRecyclerClickListener;
import com.tepth.remote.ui.recycler.grid.GridItemType;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Description:围栏踩点功能
 *
 * @author Hequn.Lee
 * @date 2018/11/24
 */
@SuppressLint("SetTextI18n")
public class PickDelegate extends BasePermissionCheckerDelegate implements MultipleRecyclerClickListener {

    @BindView(R2.id.rv_project)
    RecyclerView recyclerView = null;
    @BindView(R2.id.linear_fences_layout)
    LinearLayoutCompat linearFencesLayout = null;
    @BindView(R2.id.mapView)
    MapView mMapView = null;
    @BindView(R2.id.linear_fences_bottom)
    LinearLayoutCompat linearLayoutBottom = null;
    @BindView(R2.id.linear_fences_seek)
    LinearLayoutCompat linearLayoutSeek = null;
    @BindView(R2.id.linear_fences_operate)
    LinearLayoutCompat linearLayoutOperate = null;
    @BindView(R2.id.edit_radius)
    AppCompatEditText editRadius = null;
    @BindView(R2.id.linear_fences_radius)
    LinearLayoutCompat linearLayoutRadius = null;
    @BindView(R2.id.text_fences_lat_lng)
    AppCompatTextView textLatLng = null;

    /**
     * 百度地图控件
     */
    private BaiduMap baiduMap;
    private MultipleRecyclerAdapter mAdapter = null;
    private int lastProjectIndex = -1;
    private int lastFenceIndex = -1;
    /**
     * 选中的围栏
     */
    private Fences selectFence = null;
    /**
     * 画圆的圆心
     */
    private Marker centerMarker = null;
    /**
     * 踩点的多边形围栏集合
     */
    private ArrayList<LatLng> polygonList = new ArrayList<>();
    /**
     * 多边形Mark集合
     */
    private ArrayList<Marker> polygonMarks = new ArrayList<>();
    /**
     * 本人定位点
     */
    private LatLng latlng = null;
    /**
     * 选中的多边形的某个点
     */
    private Marker selectMark = null;
    /**
     * 要写入XML的集合
     */
    private ArrayList<ElementBean> writeBeans = new ArrayList<>();
    private boolean isFirstLoc = true;
    private DialogLoader mDialogLoader = null;

    public static PickDelegate create(LatLng latLng) {
        final PickDelegate contentDelegate = new PickDelegate();
        final Bundle bundle = new Bundle();
        bundle.putParcelable(AttendanceDelegate.CENTER, latLng);
        contentDelegate.setArguments(bundle);
        return contentDelegate;
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_pick;
    }

    @OnClick({R2.id.linear_fences_pick, R2.id.linear_fences_submit,
            R2.id.linear_fences_delete, R2.id.linear_fences_cancel,
            R2.id.button_refresh})
    void onClick(View view) {
        final int id = view.getId();
        if (id == R.id.linear_fences_pick) {
            pick();
        } else if (id == R.id.linear_fences_submit) {
            submit(writeBeans);
        } else if (id == R.id.linear_fences_delete) {
            if (selectMark == null) {
                return;
            }
            if (selectFence.getEFB_Type() == 1) {
                centerMarker = null;
                FileUtil.deleteXml(selectFence.getEFB_ID() + "");
                baiduMap.clear();
            } else {
                final int userId = ConfigManager.getInstance().getUid();
                polygonList = deletePoint(polygonList, selectMark.getPosition());
                polygonMarks.clear();
                writeBeans.clear();
                // 多边形点的集合
                for (int i = 0; i < polygonList.size(); i++) {
                    // 集合打点
                    polygonMarks.add((Marker) baiduMap
                            .addOverlay(MarkerOverlay.builderPointByTypeFromBitmap(
                                    new LatLng(polygonList.get(i).latitude,
                                            polygonList.get(i).longitude), 0)));
                    writeBeans.add(new ElementBean(polygonList.get(i).latitude,
                            polygonList.get(i).longitude, userId, String.valueOf(selectFence.getEFB_ID()),
                            0, i + 1 + ""));
                }
                baiduMap.clear();
                OverlayOptions options;
                if (selectFence.getEFB_Type() == 3) {
                    options = DrawOverlay.drawPolygon(polygonList);
                } else {
                    options = DrawOverlay.drawPolyline(polygonList);
                }
                if (options != null) {
                    baiduMap.addOverlay(options);
                }
                if (polygonMarks.size() != 0) {
                    for (int i = 0; i < polygonMarks.size(); i++) {
                        baiduMap.addOverlay(MarkerOverlay.builderPointByTypeFromBitmap(polygonMarks.get(i).getPosition(), 0));
                    }
                }
                writeXml(writeBeans, selectFence.getEFB_ID());
            }
            if (linearLayoutSeek != null) {
                linearLayoutSeek.setVisibility(View.VISIBLE);
            }
            if (linearLayoutOperate != null) {
                linearLayoutOperate.setVisibility(View.GONE);
            }
            if (textLatLng != null) {
                textLatLng.setVisibility(View.GONE);
            }
            if (selectFence.getEFB_Type() == 1 && linearLayoutRadius != null) {
                linearLayoutRadius.setVisibility(View.VISIBLE);
            }
        } else if (id == R.id.linear_fences_cancel) {
            if (linearLayoutOperate != null) {
                linearLayoutOperate.setVisibility(View.GONE);
            }
            if (linearLayoutSeek != null) {
                linearLayoutSeek.setVisibility(View.VISIBLE);
            }
            if (selectFence.getEFB_Type() == 1 && linearLayoutRadius != null) {
                linearLayoutRadius.setVisibility(View.VISIBLE);
            }
            if (textLatLng != null) {
                textLatLng.setVisibility(View.GONE);
            }
            selectMark = null;
            for (Marker temp : polygonMarks) {
                temp.setIcon(BitmapDescriptorBuilder.getBitmapDescriptorBluePointFromResource());
            }
            if (centerMarker != null) {
                centerMarker.setIcon(BitmapDescriptorBuilder.getBitmapDescriptorBluePointFromResource());
            }
        } else {
            refreshConfig();
        }
    }

    private void pick() {
        if (latlng == null) {
            return;
        }
        if (selectFence == null) {
            ToastUtils.showShort("未选择围栏");
            return;
        }
        final int userId = ConfigManager.getInstance().getUid();
        int radius = 0;
        final int type = selectFence.getEFB_Type();
        if (type == 1) {
            if (centerMarker != null) {
                baiduMap.clear();
            }
            if (editRadius != null && editRadius.getText() != null && editRadius.getText().toString().length() != 0) {
                radius = Integer.parseInt(editRadius.getText().toString());
            }
            if (radius == 0) {
                ToastUtils.showShort("请输入半径");
                return;
            }
            OverlayOptions circle = DrawOverlay.drawCircle(latlng, radius);
            if (circle != null) {
                // 画圆
                baiduMap.addOverlay(circle);
                // 画圆心
                centerMarker = (Marker) baiduMap.addOverlay(MarkerOverlay
                        .builderPointByTypeFromBitmap(latlng, 0));
                // 圆心居中
                baiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(latlng, 15.0f));

            } else {
                centerMarker = null;
            }
        } else {
            // 判断这个点是否采集过
            boolean isContains = false;
            if (polygonList.size() != 0) {
                for (LatLng temp : polygonList) {
                    if (temp.latitude == latlng.latitude
                            && temp.longitude == latlng.longitude) {
                        isContains = true;
                        break;
                    }
                }
            }
            if (isContains) {
                ToastUtils.showShort("该点已采集");
                return;
            }
            baiduMap.clear();
            polygonMarks.clear();
            polygonList.add(latlng);
            for (int i = 0; i < polygonList.size(); i++) {
                // 集合打点
                final Marker oneMark = (Marker) baiduMap
                        .addOverlay(MarkerOverlay.builderPointByTypeFromBitmap(polygonList.get(i), 0));
                polygonMarks.add(oneMark);
            }
            OverlayOptions options;
            if (type == 3) {
                options = DrawOverlay.drawPolygon(polygonList);
            } else {
                options = DrawOverlay.drawPolyline(polygonList);
            }
            baiduMap.addOverlay(options);
        }
        writeBeans.add(new ElementBean(latlng.latitude, latlng.longitude, userId,
                String.valueOf(selectFence.getEFB_ID()), radius, "1"));
        writeXml(writeBeans, selectFence.getEFB_ID());
        ToastUtils.showShort("采集成功");
    }

    private void submit(ArrayList<ElementBean> list) {
        if (list.size() > 0) {
            final ArrayList<JSONObject> pointList = new ArrayList<>();
            for (ElementBean bean : list) {
                pointList.add(bean.toJSONObject());
            }
            final JSONObject jsonObject = new JSONObject();
            jsonObject.put("obj", pointList);
            final String jsonString = JSON.toJSONString(jsonObject,
                    SerializerFeature.WriteMapNullValue,
                    SerializerFeature.WriteNullListAsEmpty,
                    SerializerFeature.WriteNullStringAsEmpty,
                    SerializerFeature.WriteNullBooleanAsFalse,
                    SerializerFeature.WriteNullNumberAsZero,
                    SerializerFeature.WriteNonStringValueAsString);
            ControlSingleThread.getThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    postSubmit(jsonString);
                }
            });
        } else {
            ToastUtils.showShort("请先采集坐标点");
        }
    }

    private void refreshConfig() {
        mDialogLoader.showProgressDialog(false, "正在加载", "");
        RxRetrofitClient.builder()
                .url(ApiDictionary.API_GET_CONFIG)
                .params("Imei", ConfigManager.getInstance().getPhoneId())
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(Object value) {
                        mDialogLoader.clearDialog();
                        final Config config = new ObjectConverter<Config>().convert(JSON.toJSONString(value),
                                new TypeReference<Config>() {
                                });
                        ConfigManager.getInstance()
                                .setRealName(config.getRealName())
                                .setUid(config.getUid())
                                .setPhoneId(config.getPhoneId())
                                .setIsBm(config.getIsBm())
                                .setIsZj(config.getIsZj())
                                .setProjects(config.getProjects());
                        final ArrayList<Project> allData = config.getProjects();
                        PickDataConvert convert = new PickDataConvert();
                        mAdapter.setNewData(convert.setData(convert.convertProjectToObject(allData)).convert());
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mDialogLoader.clearDialog();
                    }
                })
                .builder()
                .get();
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        readStorageWithCode();
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        EventBus.getDefault().register(this);
        mDialogLoader = new DialogLoader(getContext());
        final Bundle bundle = getArguments();
        initRecyclerView();
        if (bundle != null) {
            latlng = bundle.getParcelable(AttendanceDelegate.CENTER);
            if (latlng == null) {
                latlng = new LatLng(29.566483, 106.564186);
            }
        } else {
            latlng = new LatLng(29.566483, 106.564186);
        }
        initMap();
    }

    private void initRecyclerView() {
        final ArrayList<Project> allData = ConfigManager.getInstance().getProjects();
        final PickDataConvert converter = new PickDataConvert();
        mAdapter = MultipleRecyclerAdapter.create(converter.setData(
                converter.convertProjectToObject(allData)).convert(), this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        //3.给GridLayoutManager设置滑动的方向
        linearLayoutManager.setOrientation(GridLayoutManager.HORIZONTAL);
        //4.为recyclerView设置布局管理器
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(mAdapter);
        //一个一个的滑动（完全ViewPager效果）
        final PagerSnapHelper snapHelper = new PagerSnapHelper();
        //其他都与RecyclerView一样，只需要绑定下就行
        snapHelper.attachToRecyclerView(recyclerView);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                // 项目数量大于1并且当停止滑动时
                if (mAdapter.getItemCount() > 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                    lastFenceIndex = -1;
                    resetMap();
                    if (baiduMap != null) {
                        baiduMap.clear();
                    }
                    if (linearFencesLayout != null) {
                        linearFencesLayout.removeAllViews();
                        linearFencesLayout.setVisibility(View.GONE);
                    }
                    if (linearLayoutBottom != null) {
                        linearLayoutBottom.setVisibility(View.GONE);
                    }
                    if (lastProjectIndex >= 0 && mAdapter != null) {
                        final MultipleItemEntity entity = mAdapter.getItem(lastProjectIndex);
                        if (entity != null) {
                            entity.setField(MultipleFields.IS_PULL, false);
                            mAdapter.setData(lastProjectIndex, entity);
                        }
                        lastProjectIndex = -1;
                    }
                }
            }
        });
    }

    private void initMap() {
        baiduMap = mMapView.getMap();
        // 开启定位图层
        baiduMap.setMyLocationEnabled(true);
        // 隐藏缩放控件
        mMapView.showScaleControl(false);
        // 隐藏比例尺控件
        mMapView.showZoomControls(false);
        baiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(latlng, 15.0f));
        baiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                for (Marker temp : polygonMarks) {
                    temp.setIcon(BitmapDescriptorBuilder.getBitmapDescriptorBluePointFromResource());
                }
                marker.setIcon(BitmapDescriptorBuilder.getBitmapDescriptorGreenPointFromResource());
                linearLayoutSeek.setVisibility(View.GONE);
                linearLayoutOperate.setVisibility(View.VISIBLE);
                final LatLng latLng = marker.getPosition();
                final StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append(String.format(Locale.CHINA, "经度:%f", latLng.longitude))
                        .append(" ")
                        .append(String.format(Locale.CHINA, "纬度:%f", latLng.latitude));
                textLatLng.setText(stringBuffer);
                textLatLng.setVisibility(View.VISIBLE);
                if (selectFence.getEFB_Type() == 1) {
                    linearLayoutRadius.setVisibility(View.GONE);
                }
                selectMark = marker;
                return true;
            }
        });
        baiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                for (Marker temp : polygonMarks) {
                    temp.setIcon(BitmapDescriptorBuilder.getBitmapDescriptorBluePointFromResource());
                }
                if (linearLayoutSeek != null) {
                    linearLayoutSeek.setVisibility(View.VISIBLE);
                }
                if (linearLayoutOperate != null) {
                    linearLayoutOperate.setVisibility(View.GONE);
                }
                if (textLatLng != null) {
                    textLatLng.setVisibility(View.GONE);
                }
                if (selectFence != null) {
                    if (selectFence.getEFB_Type() == 1 && linearLayoutRadius != null) {
                        linearLayoutRadius.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });
    }

    @Override
    public void onclickListener(MultipleFields type, int position) {
        switch (type) {
            case BACK:
                pop();
                break;
            case PULL:
                if (linearFencesLayout != null) {
                    linearFencesLayout.removeAllViews();
                }
                final MultipleItemEntity entity = mAdapter.getItem(position);
                if (entity != null) {
                    final boolean isPull = entity.getField(MultipleFields.IS_PULL);
                    if (isPull) {
                        if (linearLayoutBottom != null) {
                            linearLayoutBottom.setVisibility(View.GONE);
                        }
                        if (linearFencesLayout != null) {
                            linearFencesLayout.setVisibility(View.GONE);
                        }
                        lastProjectIndex = -1;
                    } else {
                        lastProjectIndex = position;
                        if (linearFencesLayout != null) {
                            linearFencesLayout.setVisibility(View.VISIBLE);
                            final Project project = entity.getField(MultipleFields.PROJECT);
                            final ArrayList<Fences> fences = project.getUserElecFences();
                            final int size = fences.size();
                            for (int i = 0; i < size; i++) {
                                fences.get(i).setSort(i);
                                linearFencesLayout.addView(getTextView(fences.get(i), i));
                            }
                        }
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onLoadRecyclerError(String msg) {

    }

    @Override
    public void onclickViewPagerListener(GridItemType type) {
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateLocation(LocationEvent event) {
        if (baiduMap != null) {
            final BDLocation location = event.getBDLocation();
            final MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(0)
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            latlng = new LatLng(location.getLatitude(), location.getLongitude());
            baiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                final MyLocationConfiguration config = new MyLocationConfiguration(
                        MyLocationConfiguration.LocationMode.NORMAL, true, BitmapDescriptorFactory
                        .fromResource(R.mipmap.icon_location));
                baiduMap.setMyLocationConfiguration(config);
                isFirstLoc = false;
            }
        }
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    private AppCompatTextView getTextView(final Fences fences, final int fencePosition) {
        final AppCompatTextView textView = new AppCompatTextView(getProxyActivity());
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        textView.setGravity(Gravity.CENTER);
        textView.setTextColor(ResourcesUtil.getColorFromResources(getContext(), R.color.text_fences));
        textView.setTextSize(20);
        textView.setSingleLine(true);
        textView.setBackgroundResource(R.drawable.text_fences);
        textView.setText(fences.getEFB_Name());
        textView.setTypeface(Typeface.DEFAULT);
        textView.setPadding(0, 10, 0, 10);
        textView.setLayoutParams(lp);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final int projectPosition = fences.getSort();
                if (projectPosition != lastFenceIndex) {
                    resetMap();
                    lastFenceIndex = projectPosition;
                    if (linearFencesLayout != null) {
                        final int size = linearFencesLayout.getChildCount();
                        for (int i = 0; i < size; i++) {
                            AppCompatTextView text = (AppCompatTextView) linearFencesLayout.getChildAt(i);
                            text.setTextColor(ResourcesUtil.getColorFromResources(getContext(), R.color.text_fences));
                        }
                        final AppCompatTextView childView = (AppCompatTextView) linearFencesLayout.getChildAt(fencePosition);
                        childView.setTextColor(ResourcesUtil.getColorFromResources(getContext(), R.color.home_color));
                    }
                    if (mAdapter != null) {
                        final MultipleItemEntity entity = mAdapter.getItem(lastProjectIndex);
                        if (entity != null) {
                            final Project project = entity.getField(MultipleFields.PROJECT);
                            final ArrayList<Fences> fences = project.getUserElecFences();
                            linearLayoutBottom.setVisibility(View.VISIBLE);
                            linearLayoutSeek.setVisibility(View.VISIBLE);
                            linearLayoutOperate.setVisibility(View.GONE);
                            selectFence = fences.get(fencePosition);
                            if (selectFence.getEFB_Type() == 1) {
                                linearLayoutRadius.setVisibility(View.VISIBLE);
                            } else {
                                linearLayoutRadius.setVisibility(View.GONE);
                            }
                            readXml(fences.get(fencePosition).getEFB_ID(), fences.get(fencePosition).getEFB_Type());
                        } else {
                            selectFence = null;
                        }
                    }
                }
            }
        });
        return textView;
    }

    private void readXml(final int id, final int type) {
        baiduMap.clear();
        ControlSingleThread.getThreadPool().execute(ControlSingleThread
                .getInstance()
                .setCallback(new RunnableCallback() {
                    @Override
                    public void callback() {
                        try {
                            writeBeans = XmlHandler.getInstance().readXml(String.valueOf(id));
                            Control.getHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    drawFencesFromElements(writeBeans, type);
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).getRunnable());
    }

    /**
     * 写入XML文件
     *
     * @param beans   写入集合
     * @param fenceId 围栏ID
     */
    private void writeXml(final ArrayList<ElementBean> beans, final int fenceId) {
        if (beans.size() != 0) {
            ControlSingleThread.getThreadPool().execute(ControlSingleThread
                    .getInstance()
                    .setCallback(new RunnableCallback() {
                        @Override
                        public void callback() {
                            try {
                                XmlHandler.getInstance().writeXml(beans, String.valueOf(fenceId));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).getRunnable());
        }
    }

    private void drawFencesFromElements(ArrayList<ElementBean> elementBeans, int type) {
        if (elementBeans.size() == 0) {
            return;
        }
        switch (type) {
            //画圆
            case 1:
                final LatLng center = new LatLng(elementBeans.get(elementBeans.size() - 1).getLatitude(), elementBeans.get(elementBeans.size() - 1).getLongitude());
                final int radius = elementBeans.get(elementBeans.size() - 1).getRadius();
                OverlayOptions circle = DrawOverlay.drawCircle(center,
                        radius);
                if (circle != null) {
                    // 画圆
                    baiduMap.addOverlay(circle);
                    // 画圆心
                    centerMarker = (Marker) baiduMap.addOverlay(MarkerOverlay
                            .builderPointByTypeFromBitmap(center, 0));
                    // 圆心居中
                    baiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(center, 15.0f));
                } else {
                    centerMarker = null;
                }
                break;
            //多边形
            case 3:
                polygonList.clear();
                final int polygonSize = elementBeans.size();
                for (int i = 0; i < polygonSize; i++) {
                    final ElementBean bean = elementBeans.get(i);
                    final LatLng newLatLng = new LatLng(bean.getLatitude(), bean.getLongitude());
                    polygonList.add(newLatLng);
                    // 集合打点
                    Marker oneMark = (Marker) baiduMap
                            .addOverlay(MarkerOverlay
                                    .builderPointByTypeFromBitmap(newLatLng, 0));
                    polygonMarks.add(oneMark);
                }
                OverlayOptions polygon = DrawOverlay.drawPolygon(polygonList);
                if (polygon != null) {
                    // 画多边形
                    baiduMap.addOverlay(polygon);
                    // 居中
                    baiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(polygonList.get(0), 15.0f));
                }
                break;
            //折线
            case 4:
                polygonList.clear();
                final int polylineSize = elementBeans.size();
                for (int i = 0; i < polylineSize; i++) {
                    final ElementBean bean = elementBeans.get(i);
                    final LatLng newLatLng = new LatLng(bean.getLatitude(), bean.getLongitude());
                    polygonList.add(newLatLng);
                    // 集合打点
                    Marker oneMark = (Marker) baiduMap
                            .addOverlay(MarkerOverlay
                                    .builderPointByTypeFromBitmap(newLatLng, 0));
                    polygonMarks.add(oneMark);
                }
                OverlayOptions polyline = DrawOverlay.drawPolyline(polygonList);
                if (polyline != null) {
                    // 画多边形
                    baiduMap.addOverlay(polyline);
                    // 居中
                    baiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(polygonList.get(0), 15.0f));
                }
                break;
            default:
                break;
        }
    }

    private void resetMap() {
        polygonList.clear();
        centerMarker = null;
        polygonMarks.clear();
        writeBeans.clear();
    }

    /**
     * 从一个List<LatLng>中删除一个LatLng
     *
     * @param list  源集合
     * @param point 要删除的点
     * @return 删除后的集合
     */
    private ArrayList<LatLng> deletePoint(ArrayList<LatLng> list, LatLng point) {
        LatLng deletePoint = null;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).latitude == point.latitude
                    && list.get(i).longitude == point.longitude) {
                deletePoint = list.get(i);
            }
        }
        if (deletePoint != null) {
            list.remove(deletePoint);
        }
        return list;
    }

    private void postSubmit(String jsonString) {
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("jsonString", jsonString));
        String urlString = "http://gps.tepth.com.cn/phoneapi/addelegps.ashx";
        StringBuilder result = new StringBuilder();
        HttpClient hc = new DefaultHttpClient();
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
        HttpPost hp = new HttpPost(urlString);
        HttpEntity he;
        try {
            he = new UrlEncodedFormEntity(params, "utf-8");
            hp.setEntity(he);
            HttpResponse response = hc.execute(hp);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity het = response.getEntity();
                InputStream is = het.getContent();
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(is));
                String readLine;
                while ((readLine = br.readLine()) != null) {
                    result.append(readLine);
                }
                is.close();
                showResult("提交成功", 0);
            } else {
                showResult("提交失败", 1);
            }
        } catch (Exception e) {
            BuglyLog.e("HttpException", "====接口地址====：" + urlString);
            CrashReport.postCatchedException(e);
            e.printStackTrace();
            showResult("提交失败", 1);
        }
    }

    private void showResult(final String result, final int type) {
        Control.getHandler().post(new Runnable() {
            @Override
            public void run() {
                if (type == 0) {
                    mDialogLoader.showSuccess(result, "", new IDialogClickListener() {
                        @Override
                        public void onClick() {
                            mDialogLoader.clearDialog();
                        }
                    });
                } else {
                    mDialogLoader.showFailed(result, "", new IDialogClickListener() {
                        @Override
                        public void onClick() {
                            mDialogLoader.clearDialog();
                        }
                    });
                }

            }
        });
    }
}
